﻿$(document).ready(function () {


    $("a#lnkAddMoreFlows").click(function () {
        addFlowRow();
        // updateSubmitFlowsLink();
    });
    $("input#btnSave").click(function () {

        var result = validateControls();
        if (result) {
            submitFlows();
            // Go to code-behind
            return true;
        }
        else {
            return false;

        }

    });

    $("a#lnkAddMoreFlows").click();

});

function addFlowRow() {
    var row = $("#flow-item").clone();
    var lnkClose = $("<a class='lnkClose'>Close</a>");

    lnkClose.click(function () {
        // Close current one
        $(this).parent().parent().remove();
        // updateSubmitFlowsLink();
    });

    row.find(".section").prepend(lnkClose);
    row.attr("class", "flow-row");
    row.removeAttr("id");
    row.show();

    $(".multi-flows").append(row);

}

function validateControls() {
    var result = true;
    $(".multi-flows .flow-row").each(function (index) {
        var str = $.trim($("input#txtName", this).val());

        if (str == '') {
            $("span#vldAmount", this).show();
            result = false;
        }
        else {
            $("span#vldAmount", this).hide();
        }


    });

    // Return false, if submit empty set
    if ($(".multi-flows .flow-row").length == 0)
        result = false;


    return result;
}

function submitFlows() {
    var flowsRaw = [];

    $(".multi-flows .flow-row").each(function (index) {
        var name = $.trim($("input#txtName", this).val());
        var unit = $("select#ddlUnit", this).val();

        var item = {};
        item.Name = name;
        item.Unit = unit;

        flowsRaw.push(item);
    });

    $("#txtFlowsRaw").val(JSON.stringify(flowsRaw));

}